/*
 * FormHandler.java
 *
 * Copyright (C) 2007 Irving Bunton
 * http://code.google.com/p/jlogmicro/source
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
// Expand to define MIDP define
@DMIDPVERS@
// Expand to define CLDC define
@DCLDCVERS@
// Expand to define logging define
@DLOGDEF@
//#ifdef DLOGGING
package net.sf.jlogmicro.util.logging;

import java.util.Date;
import java.util.Vector;
import java.util.Hashtable;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

import net.sf.jlogmicro.util.logging.Handler;
import net.sf.jlogmicro.util.logging.LogRecord;

public class FormHandler extends BufferedHandler {

	public FormHandler() {
	}

	public Object openView(boolean append) {
		if (view == null) {
			view = new FormSync(name);
		}
		return view;
	}

	public void closeView() {
		view = null;
	}

	public void removeView() {
		if (view == null) {
			openView(false);
		}
		Form fview = (Form)view;
		//#ifdef DMIDP20
		fview.deleteAll();
		//#else
		int flen = fview.size();
		for (int i = 0; i < flen; i++) {
			fview.delete(0);
		}
		//#endif
		closeView();
	}

	public void publish(LogRecord record) {
		synchronized(this) {
			Form form = (Form)view;
			int fsize = form.size();
			if ((maxEntries != 0) && (fsize >= maxEntries)) {
				form.delete(fsize - 1);
			}
			try {
				String fmtRec = formatter.format(record);
				form.insert(0, new StringItem(null, formatter.format(record) + "\n"));
			} catch (OutOfMemoryError e) {
				record.setMessage("Out of memory.  Cannot log message.");
				form.insert(0, new StringItem(null, formatter.format(record) + "\n"));
			}
		}
	}

	public class FormSync extends Form {
		public FormSync(String title) {
			super(title);
		}

		public void insert(int ix, Item item) {
			synchronized(this) {
				super.insert(ix, item);
			}
		}

		public Item get(int ix, Item item) {
			synchronized(this) {
				return super.get(ix);
			}
		}

	}

}
//#endif
